package com.example.android

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import com.example.android.FlutterMgr.ENGINE_ID
import com.example.android.FlutterMgr.setInitRoute
import com.example.android.androidview.MyViewFlutterPlugin
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine

//class MyFlutterActivity : FlutterFragmentActivity() {
class MyFlutterActivity : FlutterActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        // 注册为Flutter插件
        flutterEngine.plugins.add(MyViewFlutterPlugin())
    }
    override fun onFlutterUiDisplayed() {
        super.onFlutterUiDisplayed()
        println("onFlutterUiDisplayed")
        // flutter第一帧绘制完成回调
        // 设置 Flutter 界面入口，注意不要在 onCreate 方法中调用，否则
        // Flutter 入口不会更新。
        val route = intent.getStringExtra(EXTRA_ROUTE)
        setInitRoute(route)
    }

    override fun onFlutterUiNoLongerDisplayed() {
        super.onFlutterUiNoLongerDisplayed()
        //当 Flutter 界面不再显示时调用。
    }

    companion object {
        const val EXTRA_CACHED_ENGINE_ID: String = "cached_engine_id"
        const val EXTRA_ROUTE: String = "extra_route"
        const val EXTRA_DESTROY_ENGINE_WITH_ACTIVITY: String = "destroy_engine_with_activity"

        fun open(context: Context, route: String?) {
            val intent = Intent(context, MyFlutterActivity::class.java)
                .putExtra(EXTRA_CACHED_ENGINE_ID, ENGINE_ID) // 路由
                .putExtra(EXTRA_ROUTE, route) // Activity 销毁时保留 FlutterEngine
                .putExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, false)
            context.startActivity(intent)
        }
    }

//    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
//        MethodChannelMgr.callFlutter("keyEvent", null)
//        return super.dispatchKeyEvent(event)
//    }
}
